#include <iostream>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string>
#include <cstring>

void *mymalloc(int size)
{
    // 映射到匿名文件
    void *ret = ::mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
    if (ret == MAP_FAILED)
    {
        std::cerr << "映射失败" << "\n";
        exit(1);
    }
    return ret;
}
void myfree(void *addr, size_t size)
{
    if (addr == nullptr)
        return;
    if (::munmap(addr, size) == -1)
    {
        std::cerr << "释放失败" << "\n";
        exit(2);
    }
}

int main()
{
    int size = 1024;
    char *ptr = (char *)mymalloc(size);

    // 使⽤分配的内存（这⾥只是简单地打印指针值）
    printf("Allocated memory at address: %p\n", ptr);
    // ... 在这⾥可以使⽤ptr指向的内存 ...
    memset(ptr, 'A', size);
    for (int i = 0; i < size; i++)
    {
        printf("%c ", ptr[i]);
        sleep(1);
    }
    myfree(ptr,size);
    return 0;
}
